package com.fingard.dsp.bank.directbank.hrbb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HRBB01Transaction extends HRBB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            HRBB01Header header = new HRBB01Header();
            header.bsnCode = "CBE002";
            header.serialNo = p_req7516.reqHeader.transSeqID;
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                //int tmpPageBeginPos = 1;//查询起始条
                int tmpNowReadedCount = 0;//已读条数
                //int tmpPageShowNum = 5;//每页显示记录数
                boolean tmpQryNext = true;
                Map<String, Integer> tmpTotalNum = new HashMap<String, Integer>();
                while (tmpNowReadedCount == 0 || tmpNowReadedCount < tmpTotalNum.get("totalCount")) {//分页查询
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发送银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("ReqParam");
                    xmlWriter.writeElementString("accountNo", p_req7516.actNum);
                    xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                    String tmpCur = convertCurToBank(getBankConfig().getMapKeyByValue("curActMapping", p_req7516.actNum));
                    xmlWriter.writeElementString("currencyType", tmpCur);
                    xmlWriter.writeElementString("turnPageBeginPos", String.valueOf(tmpNowReadedCount + 1));
                    xmlWriter.writeElementString("turnPageShowNum", getBankConfig().getValueAsString("pageSize"));
                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    if (tmpStrRet[0].length() == 0) {
                        if (getRet(tmpStrRet[1])) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRets[2], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String tmpTotalNumText = tmpBkReader.getFirstText("/BankData/opRep/opResult/turnPageTotalNum");
                                if (StringHelper.hasAnyChar(tmpTotalNumText)) {
                                    if (tmpTotalNum.containsKey("totalCount")) {
                                        if (tmpTotalNum.get("totalCount").intValue() != Integer.valueOf(tmpTotalNumText).intValue()) {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "相同条件前后查出来的总数不一致";
                                            break;
                                        }
                                    } else {
                                        if ("0".equals(tmpTotalNumText)) {
                                            break;
                                        }
                                        tmpTotalNum.put("totalCount", Integer.valueOf(tmpTotalNumText));
                                    }
                                    while (tmpBkReader.read("/BankData/opRep/opResult/list/row")) {
                                        ++tmpNowReadedCount;
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        tmpRetDetail.actNum = p_req7516.actNum;
                                        tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("partnerAccNo");
                                        tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("partnerAccName");
                                        tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("partnerAccOpenBank");
                                        String tmpTranDate = tmpBkReader.readedXElement.getSingleText("transferDate");
                                        tmpRetDetail.tranDate = tmpTranDate;
                                        String tmpTranTime = tmpBkReader.readedXElement.getSingleText("transferTime");//HH:mm:ss
                                        tmpTranTime = tmpTranDate + " " + Format.Time8Format.format(Format.Time8Format.parse(tmpTranTime));//yyyy-MM-dd HH:mm:ss
                                        tmpRetDetail.tranTime = tmpTranTime;
                                        tmpRetDetail.valueDate = tmpTranDate;//起息日没有返回就用交易日
                                        tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance");

                                        String tmpTranAmt = tmpBkReader.readedXElement.getSingleText("tranAmt");
                                        String tmpDCFlag = tmpBkReader.readedXElement.getSingleText("DCFlag");
                                        if ("C".equals(tmpDCFlag)) {
                                            if (tmpTranAmt.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "1";
                                            } else {
                                                tmpRetDetail.cdFlag = "2";
                                            }
                                        } else if ("D".equals(tmpDCFlag)) {
                                            if (tmpTranAmt.indexOf("-") >= 0) {
                                                tmpRetDetail.cdFlag = "2";
                                            } else {
                                                tmpRetDetail.cdFlag = "1";
                                            }
                                        } else {
                                            throw new Exception("DCFlag无效：" + tmpDCFlag);
                                        }
                                        tmpRetDetail.tranAmt = tmpTranAmt.replace("-", "");

                                        String tmpPurpose = tmpBkReader.readedXElement.getSingleText("purpose");
                                        tmpRetDetail.usage = tmpPurpose;
                                        tmpRetDetail.abstr = pickupAbstr(tmpPurpose);

                                        tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("transDesc");
                                        tmpRetDetail.cur = p_req7516.actCur;
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                    //tmpPageBeginPos;

                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = "turnPageTotalNum为空";
                                    break;
                                }

                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpSbMsg.toString();
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            if (tmpRets.length >= 3) {
                                tmpRespInfo = tmpRets[1];
                            } else {
                                tmpRespInfo = tmpRets[0];
                            }
                            break;
                        }

                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
